package com.alisls.demo.springcloud.oauth.server.service.impl;

import com.alisls.demo.springcloud.oauth.server.feign.UserFeignClient;
import com.alisls.demo.springcloud.service.user.dto.user.UserPwdDTO;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * UserDetails服务接口实现类
 *
 * @author Ke Wang
 */
@Service("customUserDetailsService")
@Log4j2
public class CustomUserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private PasswordEncoder passwordEncoder;

    @Resource
    private UserFeignClient userFeignClient;

    /**
     * 根据用户名查询用户详细信息
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 通过远程客户端userFeignClient查询用户
        UserPwdDTO userPwdDTO = userFeignClient.getUserWithPwdByUsername(username);
        log.info("认证中心查询用户结果：{}", userPwdDTO);
        if (userPwdDTO == null) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // TODO 查询用户权限
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("product:listProducts");

        String password = userPwdDTO.getPassword();
        return new User(username, password, grantedAuthorities);
    }

}
